import Vue from 'vue'
import Vuex from 'vuex'
import service from '@/utils/request'
import router from '@/router'

Vue.use(Vuex)

// 安全解析 JSON 数据
const safeJsonParse = (jsonString, defaultValue = {}) => {
  if (!jsonString) return defaultValue
  try {
    return JSON.parse(jsonString)
  } catch (error) {
    console.error('JSON 解析失败:', error)
    console.error('错误数据:', jsonString)
    return defaultValue
  }
}

export default new Vuex.Store({
  state: {
    userData: safeJsonParse(localStorage.getItem('userData')) || {
      id: null,
      username: null,
      avatar: null,
      email: null,
      token: null,
      fileList: [],
      storageInfo: {
        usedStorage: 0,
        totalStorage: 100
      }
    }
  },

  getters: {
    // 保留 token 和登录状态判断
    isUserLoggedIn(state) {
      return !!state.userData?.token;
    },
    token: state => state.userData.token,
    id: state => state.userData.id,
    username: state => state.userData.username,
    avatar: state => state.userData.avatar,
    email: state => state.userData.email,
    fileList: state => state.userData.fileList,
    storage: state => state.userData.storageInfo,

    // 文件筛选相关的 getter
    activeFiles: state => (state.userData.fileList || []).filter(file => !file.isDeleted),
    starredFiles: state => (state.userData.fileList || []).filter(file => file.isStarred),
    sharedFiles: state => (state.userData.fileList || []).filter(file => file.isShared),
    trashFiles: state => (state.userData.fileList || []).filter(file => file.isDeleted)
  },

  mutations: {
    UPDATE_USER_DATA(state, userData) {
      state.userData = { ...state.userData, ...userData };
    },
    initUserData(state, userData) {
      state.userData = userData
      // 其他初始化逻辑
    },
    refreshUserData(state) {
      const rawData = localStorage.getItem('userData');
      const userData = safeJsonParse(rawData, {});
      state.userData = { ...state.userData, ...userData };
      localStorage.setItem('userData', JSON.stringify(state.userData));
    },
    updateUserData(state, partialData) {
      state.userData = { ...state.userData, ...partialData }
      localStorage.setItem('userData', JSON.stringify(state.userData))
    },
    updateFileStatus(state, { fileName, isStarred }) {
      const fileIndex = state.userData.fileList.findIndex(
          file => file.fileName === fileName
      );
      if (fileIndex !== -1) {
        state.userData.fileList[fileIndex] = {
          ...state.userData.fileList[fileIndex],
          isStarred: isStarred
        };
        localStorage.setItem('userData', JSON.stringify(state.userData));
      }
    },
    UPDATE_FILE_STAR(state, { fileName, isStarred }) {
      const file = state.userData.fileList.find(
          item => item.fileName === fileName
      );
      if (file) {
        file.isStarred = isStarred;
        localStorage.setItem('userData', JSON.stringify(state.userData));
      }
    },
    updateUsername(state, username) {
      state.userData.username = username;
      localStorage.setItem('userData', JSON.stringify(state.userData));
    },
    updateAvatar(state, avatar) {
      state.userData.avatar = avatar;
      localStorage.setItem('userData', JSON.stringify(state.userData));
    },
    logout(state) {
      // 清除localStorage
      localStorage.removeItem('userData')
      // 重置Vuex状态
      state.userData = {
        id: null,
        username: null,
        avatar: null,
        email: null,
        token: null,
        fileList: [],
        storageInfo: {
          usedStorage: 0,
          totalStorage: 100
        }
      }
    }
  },

  actions: {
    updateUserItem({ commit }, payload) {
      commit('UPDATE_USER_DATA', payload);
    },
    // 保留登出功能
    logout({ commit }) {
      commit('logout')
      // 跳转到登录页
      router.push('/login')
    },

    updateFileStarStatus({ commit }, { fileName, isStarred }) {
      commit('UPDATE_FILE_STAR', { fileName, isStarred });
    },

    /**
     * 添加新文件并更新存储使用量
     */
    addFile({ state, commit }, file) {
      const newFileList = [...state.userData.fileList, file]
      const sizeNum = parseFloat(file.fileSize)
      const sizeInGB = sizeNum / 1024
      const newUsed = Math.min(
          state.userData.storageInfo.usedStorage + sizeInGB,
          state.userData.storageInfo.totalStorage
      )
      commit('updateUserData', {
        fileList: newFileList,
        storageInfo: {
          ...state.userData.storageInfo,
          usedStorage: newUsed
        }
      })
    },

    /**
     * 删除文件（标记为已删除）
     */
    async deleteFile({ state, commit }, fileId) {
      await service.post('/files/delete', { fileId })
      const updatedList = state.userData.fileList.map(file =>
          file.fileId === fileId ? { ...file, isDeleted: true } : file
      )
      commit('updateUserData', { fileList: updatedList })
    },

    /**
     * 切换文件收藏状态
     */
    async toggleStar({ state, commit }, fileName) {
      try {
        if (!state.userData.email) {
          throw new Error('用户信息缺失');
        }
        const response = await service.post('/files/toggle-star', {
          fileName,
          email: state.userData.email
        });
        const { isStarred } = response.data || {};
        if (typeof isStarred !== 'boolean') {
          throw new Error('无效的响应格式');
        }
        const updatedFiles = state.userData.fileList.map(file =>
            file.fileName === fileName ? { ...file, isStarred } : file
        );
        commit('updateUserData', { fileList: updatedFiles });
        return isStarred;
      } catch (error) {
        console.error('收藏状态更新失败:', error);
        throw error;
      }
    },

    /**
     * 切换文件共享状态
     */
    async shareFile({ state, commit }, { fileName, email, isShared }) {
      try {
        await service.post('/share', {
          fileName,
          email: state.userData.email,
          isShared: isShared !== undefined ? isShared : true
        });
        const updatedFiles = state.userData.fileList.map(file =>
            file.fileName === fileName ? { ...file, isShared } : file
        );
        commit('updateUserData', { fileList: updatedFiles });
      } catch (error) {
        console.error('共享状态同步失败:', error);
        throw error;
      }
    },

    /**
     * 创建新文件夹
     */
    createFolder({ state, commit }, folderName) {
      const newFolder = {
        fileId: Date.now().toString(),
        fileName: folderName,
        fileType: 'folder',
        fileSize: '0 MB',
        lastModified: new Date().toLocaleString(),
        isStarred: false,
        isShared: false,
        isDeleted: false
      }
      commit('updateUserData', {
        fileList: [...state.userData.fileList, newFolder]
      })
    }
  }
})